#if !defined(ServerHeader)
#define ServerHeader

#include "globals.h"
#include "node.h"
#include "rules.h"

class SinglogServerThread;

void *server (SinglogServerThread*);

class SinglogServerThread {
public:
  SinglogServerThread (Rules &r, Globals &g) :
    rules(r), globals(g), serverThread(0) {}
  ~SinglogServerThread () {
    if(serverThread) stop ();
  }

  void start () {
    quit = false;
    threadCount = 0; // Counts server thread itself
    if(pthread_create (&serverThread, 0, (void* (*) (void*)) server, this)) {
      std::cerr << "Failed to create server thread" << std::endl;
      threadCount = 0;
    }
  }

  void stop () {
    quit = true;
    while(threadCount) // Wait until all threads ended
      sleep (250);
  }

  Rules &rules;
  Globals &globals;

  pthread_t serverThread;
  bool volatile quit;
  int volatile threadCount;
};

class Talker {
public:
  Talker (SinglogServerThread &sst, int sock) : server(sst), socket(sock) {}

  SinglogServerThread &server;
  int socket;
};

#endif
